package com.mvp.java.services;

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

@Service
public class TextToSpeechService {

    /**
     * 文字转语音文件
     * @param text 输入文本
     * @return 错误map
     */
    public Map<String ,Object> textToSpeech(String text){
        int exitCode = 1;
        String msg = null;
        Map<String ,Object> resultMap = new HashMap<>();
        try {
            String speechSubscriptionKey = "bd6fe577317c4f1dba23b9176228c0ab";
            String serviceRegion = "eastasia";
            String lang = "zh-CN";

            SpeechConfig speechConfig = SpeechConfig.fromSubscription(speechSubscriptionKey, serviceRegion);
            speechConfig.setSpeechSynthesisLanguage(lang);
            AudioConfig audioConfig = AudioConfig.fromWavFileOutput("./output/speech_"+ new Date().getTime() +".wav");
            SpeechSynthesizer synth = new SpeechSynthesizer(speechConfig,audioConfig);

            Future<SpeechSynthesisResult> task = synth.SpeakTextAsync(text);
            SpeechSynthesisResult result = task.get();

            if (result.getReason() == ResultReason.SynthesizingAudioCompleted) {
                msg = "[" + text + "] 合成语音";
                exitCode = 0;
            }
            else if (result.getReason() == ResultReason.Canceled) {
                SpeechSynthesisCancellationDetails cancellation = SpeechSynthesisCancellationDetails.fromResult(result);
                System.out.println("CANCELED: Reason=" + cancellation.getReason());
                msg = "CANCELED: Reason=" + cancellation.getReason();
                if (cancellation.getReason() == CancellationReason.Error) {
                    msg = "CANCELED: ErrorCode=" + cancellation.getErrorCode() + "CANCELED: ErrorDetails=" + cancellation.getErrorDetails() + "CANCELED: Did you update the subscription info?";
                }
            }
            result.close();
            synth.close();
        } catch (Exception ex) {
            msg = "Unexpected exception: " + ex.getMessage();
        }
        resultMap.put("exitCode",exitCode);
        resultMap.put("exitMsg",msg);
        return resultMap;
    }
}
